<?php
namespace app\api\model;
use think\Db;

class BrandModel extends \app\common\model\CommonModel
{
    /**
     * 新增品牌
     * @param string $userid    用户userid
     * @param object $data      品牌数据
     * @return bool  $res       执行结果
     */
    public function add($userid,$data)
    {
        try {
            Db::startTrans();
            $brand_info = [
                'brand'         => $data['brand'],
                'remark'        => isset($data['remark']) ? $data['remark'] : '',
                'customer_id'   => isset($data['customer_id']) ? $data['customer_id'] : '',
                'create_userid' => $userid,
                'team_video'    => is_array($data['team_video']) ? implode(',',$data['team_video']) : '',
                'team_operate'  => is_array($data['team_operate']) ? implode(',',$data['team_operate']) : '',
            ];
            $brandid = Db::table('brand')->insertGetId($brand_info);
            if(!$brandid){
                Db::rollback();
                return false;
            }
            $product_info = [];
            foreach ($data['product'] as $key => $value) {
                $product_info[$key]['brand_id'] = $brandid;
                $product_info[$key]['product_name'] = $value['name'];
                $product_info[$key]['advertiser_id'] = $value['advertiser_id'];
                $product_info[$key]['plat'] = !empty($value['plat']) ? $value['plat'] : 'oceanengine';
            }
            $res = Db::table('product')->insertAll($product_info);
            if(!$res){
                Db::rollback();
                return false;    
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取一个品牌
     * @param string $userid
     * @param string $brand
     */
    public function getOne($userid,$brand)
    {
        try {
            $res = Db::table('brand')->where(['brand' => $brand])->find();
            if(!empty($res)){
                $creter = Db::table('user')->where(['userid' => $res['create_userid']])->find();
                return $creter['username'];
            }
            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 品牌列表
     * @param   string    $userid           用户userid
     * @param   int       $departmentId     部门id
     * @param   int       $pagesize         页码
     * @param   int       $page             每页数量
     * @param   string    $username         用户名
     * @param   string    $brand            品牌名
     * @return  array     $res              列表
     */
    public function getList($userid, $departmentId, $params)
    {
        try {
            $page     = isset($params['page']) && is_numeric($params['page']) ? (int)$params['page'] : 1;
            $pagesize = isset($params['pagesize']) && is_numeric($params['pagesize']) ? (int)$params['pagesize'] : 10;
            $start = ($page-1) * $pagesize;
            $field = "a.id,a.brand,a.remark,a.customer_id,a.create_userid,a.team_video,a.team_operate,a.create_time,b.username,c.customer_name";
            $sql = "SELECT 
                        {$field} 
                    FROM 
                        brand a 
                    LEFT JOIN 
                        user b 
                    ON 
                        a.create_userid = b.userid 
                    LEFT JOIN 
                        enum_customer c 
                    ON 
                        a.customer_id = c.customer_id 
                    WHERE 
                    (create_userid = '{$userid}' OR FIND_IN_SET($departmentId, team_video) > 0 OR FIND_IN_SET($departmentId, team_operate) > 0) ";
            if(!empty($params['username'])){
                $sql .= "AND b.username LIKE '%{$params['username']}%' ";
            }
            if(!empty($params['brand'])){
                $sql .= "AND a.brand LIKE '%{$params['brand']}%' ";
            }
            $order = "ORDER BY create_time DESC LIMIT {$start},{$pagesize}";
            $csql = str_replace($field,'count(*)',$sql);
            $sql .= $order;
            $res = $this->getRes($sql);
            if ($res) {
                foreach ($res as $key => $value) {
                    $res[$key]['product'] = Db::table('product')->where(['brand_id' => $value['id']])->select();
                    $res[$key]['video'] = Db::table('video')->where(['brand_id' => $value['id']])->select();
                }
            }
            $count = $this->getCount($csql);
            return $this->pageData($res,$pagesize,$page,$count);    
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
    
    /**
     * 品牌备注
     * @param   string    $userid   用户userid
     * @param   int       $brandid  品牌id
     * @param   string    $remark   备注
     */
    public function remark($userid, $brandid, $remark)
    {
        try {
            $sql = "UPDATE brand SET remark = '{$remark}' WHERE id = '{$brandid}'";
            $res = Db::execute($sql);
            if($res === false){
                return false;
            }
            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除品牌
     * @param   int       $brandid  品牌id
     * @param   string    $userid   用户userid
     */
    public function del($userid, $brandid)
    {
        try {
            // 仅能删除自己创建的品牌
            $brand_info = Db::table('brand')->where(['id' => $brandid])->find();
            if(empty($brand_info)){
                throw new \Exception('品牌不存在!');    
            }
            if($brand_info['create_userid'] != $userid){
                throw new \Exception('仅能删除自己创建的品牌!');
            }
            //存在视频不能删除
            $video_info = Db::table('video')->where(['brand_id' => $brandid])->find();
            if($video_info){
                throw new \Exception('该品牌下存在视频,不能删除!');
            }
            Db::startTrans();

            Db::table('brand')->where(['id' => $brandid,'create_userid' => $userid])->delete();

            Db::table('product')->where(['brand_id' => $brandid])->delete();

            Db::table('video')->where(['brand_id' => $brandid])->delete();
            
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }
    
    /**
     * 品牌编辑
     * @param   string    $userid       用户userid
     * @param   string    $departmentId 部门id
     * @param   array     $params       品牌信息数组
     * @return  boolean
     */
    public function edit($userid, $departmentId, $params)
    {
        try {
            // 由品牌的创建人和协同运营团队成员拥有编辑权限
            $res = Db::table('brand')->where(['id' => $params['brandid']])->find();
            if(!$res){
                throw new \Exception('品牌不存在,请检查!');
            }
            if($res['create_userid'] != $userid && !in_array($departmentId, explode(',',$res['team_operate']))){
                throw new \Exception('您没有权限编辑该品牌!');
            }
            $exist = Db::table('brand')->where(['brand' => trim($params['brand'])])->find();
            if(!empty($exist) && $exist['id'] != $params['brandid']){
                throw new \Exception('该品牌已存在!');
            }
            Db::startTrans();
            // 处理基本信息
            Db::table('brand')->where(['id' => $params['brandid']])->update([
                'brand'         =>  trim($params['brand']),
                'remark'        =>  isset($params['remark']) ? $params['remark'] : '',
                'customer_id'   => isset($params['customer_id']) ? $params['customer_id'] : '',
                'team_video'    => is_array($params['team_video']) ? implode(',',$params['team_video']) : '',
                'team_operate'  => is_array($params['team_operate']) ? implode(',',$params['team_operate']) : '',
            ]);
            // 处理产品信息
            $product_name_cloums = array_column($params['product'],'name');
            $products = Db::table('product')->where(['brand_id' => $params['brandid']])->select();
            // 先删除不要的产品数据,删除时需判断存在关联视频
            if($products){
                foreach ($products as $key => $value) {
                    // 不在提交的产品数据则删除,删除前判断是否有关联视频
                    if(!in_array($value['product_name'],$product_name_cloums)){
                        $video = Db::table('video')->where(['product_id' => $value['id']])->find();
                        if($video){
                            throw new \Exception('产品存在关联视频,不可删除!');
                        }
                        Db::table('product')->where(['id' => $value['id']])->delete();
                    }
                }
            }
            foreach ($params['product'] as $key => $value) {
                $product_info = Db::table('product')->where(['brand_id' => $params['brandid'],'product_name' => $value['name']])->find();
                if(!$product_info){
                    Db::table('product')->insert([
                        'brand_id'      => $params['brandid'],
                        'product_name'  => $value['name'],
                        'advertiser_id' => $value['advertiser_id'],
                        'plat'          => !empty($value['plat']) ? $value['plat'] : 'oceanengine',
                    ]);
                }else{
                    Db::table('product')
                        ->where(['id' => $product_info['id']])
                        ->update([
                            'advertiser_id' => $value['advertiser_id'],
                            'plat'          => !empty($value['plat']) ? $value['plat'] : 'oceanengine',
                        ]);
                }                       
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * @param int $id
     */
    public function findProduct($id)
    {
        return Db::table('video')->where(['product_id' => $id])->find();
    }

    /**
     * @param int $brand_id
     */
    public function findBrandCustomerById($brand_id)
    {
        return Db::table('brand')
                ->alias('a')
                ->join('enum_customer b','a.customer_id = b.customer_id')
                ->where(['a.id' => $brand_id])
                ->find();
    }
}